<template>
  <div class="dashboard-container">
    <!-- 数据概览区域 -->
    <div class="data-overview">
      <div class="overview-card">
        <div class="card-title">总订单数</div>
        <div class="card-value">{{ totalOrders }}</div>
      </div>
      <div class="overview-card">
        <div class="card-title">总订单金额</div>
        <div class="card-value">¥{{ totalAmount.toFixed(2) }}</div>
      </div>
      <div class="overview-card">
        <div class="card-title">平均订单金额</div>
        <div class="card-value">¥{{ avgAmount.toFixed(2) }}</div>
      </div>
      <div class="overview-card">
        <div class="card-title">数据覆盖天数</div>
        <div class="card-value">{{ dateRangeDays }}天</div>
        <div class="card-desc">
          <span class="date-range">{{ dateRangeText }}</span>
        </div>
      </div>
    </div>

    <!-- 图表容器区域 -->
    <div class="chart-container">
      <!-- 订单时间分布折线图容器 -->
      <div class="chart-item">
        <h3 class="chart-title">订单时间分布统计</h3>
        <div ref="dateChartRef" class="chart-wrapper"></div>
      </div>

      <!-- 每日订单额柱状图容器 -->
      <div class="chart-item">
        <h3 class="chart-title">每日订单额统计</h3>
        <div ref="amountChartRef" class="chart-wrapper"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import orderAPI from '../api/order_api.js'

// 辅助函数：生成两个日期之间的所有日期
const generateDatesBetween = (startDate, endDate) => {
  const dates = []
  const currentDate = new Date(startDate)

  while (currentDate <= new Date(endDate)) {
    // 格式化为 yyyy-mm-dd
    const dateString = currentDate.toISOString().split('T')[0]
    dates.push(dateString)

    // 移动到下一天
    currentDate.setDate(currentDate.getDate() + 1)
  }

  return dates
}

// 辅助函数：补全缺失的日期数据
const completeDateData = (originalData, valueKey = 'value') => {
  if (originalData.length === 0) return []

  // 转换为对象便于查找，键为日期，值为数量
  const dataMap = {}
  originalData.forEach(item => {
    dataMap[item.date] = item[valueKey]
  })

  // 找到最早和最晚的日期
  const dates = originalData.map(item => new Date(item.date))
  const startDate = new Date(Math.min(...dates))
  const endDate = new Date(Math.max(...dates))

  // 生成这段时间内的所有日期
  const allDates = generateDatesBetween(startDate, endDate)

  // 补全数据，缺失的日期填充为0
  return allDates.map(date => ({
    date,
    [valueKey]: dataMap[date] !== undefined ? dataMap[date] : 0
  }))
}

export default {
  name: 'OrderCharts',
  setup() {
    // 图表容器引用
    const dateChartRef = ref(null)
    const amountChartRef = ref(null)

    // 图表实例存储
    let dateChart = null
    let amountChart = null

    // 数据变量
    const dateData = ref([])
    const amountData = ref([])

    // 概览数据
    const totalOrders = ref(0)
    const totalAmount = ref(0)
    const avgAmount = ref(0)
    const dateRangeDays = ref(0)
    const dateRangeText = ref('')

    /**
     * 初始化折线图（订单数量）
     */
    const initDateChart = (container, data) => {
      if (!container) return null

      // 销毁已有实例
      const existingChart = echarts.getInstanceByDom(container)
      if (existingChart) {
        existingChart.dispose()
      }

      // 初始化新实例
      const chart = echarts.init(container)

      // 提取x轴和y轴数据
      const xAxisData = data.map(item => item.date)
      const seriesData = data.map(item => item.value)

      // 图表配置
      const option = {
        title: {
          text: '订单时间分布统计',
          subtext: '按时间的订单数量趋势（自动补全缺失日期）',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>订单数量: {c}单'
        },
        legend: {
          data: ['订单数量'],
          top: 30
        },
        dataZoom: [
          {
            type: 'slider',
            show: true,
            xAxisIndex: 0,
            start: 0,
            end: 100,
            height: 15,
            bottom: 10
          },
          {
            type: 'inside',
            xAxisIndex: 0,
            start: 0,
            end: 100
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData,
          axisLabel: {
            rotate: 45,
            interval: 0
          }
        },
        yAxis: {
          type: 'value',
          name: '订单数量',
          min: 0,
          axisLabel: {
            formatter: '{value} 单'
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '订单数量',
            type: 'line',
            data: seriesData,
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            emphasis: {
              symbolSize: 10
            },
            lineStyle: {
              width: 2
            },
            areaStyle: {
              opacity: 0.3
            },
            markPoint: {
              data: seriesData.map((value, index) => {
                if (value === 0) {
                  return {
                    name: '零订单',
                    value: '0单',
                    xAxis: index,
                    yAxis: value,
                    symbol: 'pin',
                    symbolSize: 40
                  }
                }
                return null
              }).filter(Boolean)
            }
          }
        ]
      }

      chart.setOption(option)
      return chart
    }

    /**
     * 初始化柱状图（订单金额）
     */
    const initAmountChart = (container, data) => {
      if (!container) return null

      // 销毁已有实例
      const existingChart = echarts.getInstanceByDom(container)
      if (existingChart) {
        existingChart.dispose()
      }

      // 初始化新实例
      const chart = echarts.init(container)

      // 提取x轴和y轴数据
      const xAxisData = data.map(item => item.date)
      const seriesData = data.map(item => item.amount)

      // 图表配置
      const option = {
        title: {
          text: '每日订单额统计',
          subtext: '按时间的订单金额趋势（自动补全缺失日期）',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>订单金额: ¥{c}'
        },
        legend: {
          data: ['订单金额'],
          top: 30
        },
        dataZoom: [
          {
            type: 'slider',
            show: true,
            xAxisIndex: 0,
            start: 0,
            end: 100,
            height: 15,
            bottom: 10
          },
          {
            type: 'inside',
            xAxisIndex: 0,
            start: 0,
            end: 100
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData,
          axisLabel: {
            rotate: 45,
            interval: 0
          }
        },
        yAxis: {
          type: 'value',
          name: '订单金额 (元)',
          min: 0,
          axisLabel: {
            formatter: '¥{value}'
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '订单金额',
            type: 'bar',
            data: seriesData,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#3398DB' },
                { offset: 1, color: '#66B2FF' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378B5' },
                  { offset: 1, color: '#4AA5E3' }
                ])
              }
            },
            // 突出显示0值点
            markPoint: {
              data: seriesData.map((value, index) => {
                if (value === 0) {
                  return {
                    name: '零金额',
                    value: '¥0',
                    xAxis: index,
                    yAxis: value,
                    symbol: 'pin',
                    symbolSize: 40
                  }
                }
                return null
              }).filter(Boolean)
            }
          }
        ]
      }

      chart.setOption(option)
      return chart
    }

    // 计算概览数据
    const calculateOverviewData = () => {
      // 计算总订单数
      const orders = dateData.value.reduce((sum, item) => sum + item.value, 0)
      totalOrders.value = orders

      // 计算总金额
      const amount = amountData.value.reduce((sum, item) => sum + item.amount, 0)
      totalAmount.value = amount

      // 计算平均订单金额
      avgAmount.value = orders > 0 ? amount / orders : 0

      // 计算日期范围
      if (dateData.value.length > 0) {
        const startDate = new Date(dateData.value[0].date)
        const endDate = new Date(dateData.value[dateData.value.length - 1].date)
        dateRangeDays.value = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1
        dateRangeText.value = `${dateData.value[0].date} 至 ${dateData.value[dateData.value.length - 1].date}`
      }
    }

    // 加载订单时间数据
    const loadDateData = async () => {
      try {
        console.log('开始请求订单时间数据...')
        const response = await orderAPI.cdate()
        console.log('订单时间数据原始响应:', response)

        // 处理订单时间数据
        const processedData = (response || []).map(item => ({
          date: item.date || '未知日期',
          value: Number(item.nums) || 0
        })).filter(item => item.date !== '未知日期')

        // 按日期排序
        processedData.sort((a, b) => new Date(a.date) - new Date(b.date))

        // 补全缺失的日期
        const completedData = completeDateData(processedData)
        dateData.value = completedData

        console.log('补全后的日期数据:', dateData.value)

        // 计算概览数据并初始化图表
        calculateOverviewData()
        dateChart = initDateChart(dateChartRef.value, dateData.value)
      } catch (error) {
        console.error('获取订单时间数据失败:', error.message)
        dateChart = initDateChart(dateChartRef.value, dateData.value)
      }
    }

    // 加载订单金额数据
    const loadAmountData = async () => {
      try {
        console.log('开始请求订单金额数据...')
        const response = await orderAPI.camount()
        console.log('订单金额数据原始响应:', response)

        // 处理订单金额数据
        const processedData = (response || []).map(item => ({
          date: item.date || '未知日期',
          amount: Number(item.amount) || 0
        })).filter(item => item.date !== '未知日期')

        // 按日期排序
        processedData.sort((a, b) => new Date(a.date) - new Date(b.date))

        // 补全缺失的日期（指定valueKey为amount）
        const completedData = completeDateData(processedData, 'amount')
        amountData.value = completedData

        console.log('补全后的金额数据:', amountData.value)

        // 计算概览数据并初始化图表
        calculateOverviewData()
        amountChart = initAmountChart(amountChartRef.value, amountData.value)
      } catch (error) {
        console.error('获取订单金额数据失败:', error.message)
        amountChart = initAmountChart(amountChartRef.value, amountData.value)
      }
    }

    // 处理窗口大小变化
    const handleResize = () => {
      if (dateChart) dateChart.resize()
      if (amountChart) amountChart.resize()
    }

    // 组件挂载时加载数据
    onMounted(() => {
      loadDateData()
      loadAmountData()
      window.addEventListener('resize', handleResize)
    })

    // 组件卸载时清理资源
    onUnmounted(() => {
      window.removeEventListener('resize', handleResize)
      if (dateChart) dateChart.dispose()
      if (amountChart) amountChart.dispose()
      dateChart = null
      amountChart = null
    })

    return {
      dateChartRef,
      amountChartRef,
      totalOrders,
      totalAmount,
      avgAmount,
      dateRangeDays,
      dateRangeText
    }
  }
}
</script>

<style scoped>
/* 整体容器样式 */
.dashboard-container {
  width: 100%;
  min-height: 100vh;
  padding: 20px;
  box-sizing: border-box;
  background-color: #f5f7fa;
}

/* 数据概览区域样式 */
.data-overview {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.overview-card {
  flex: 1;
  min-width: 250px;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.card-title {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.card-value {
  font-size: 28px;
  font-weight: 700;
  color: #333;
  margin-bottom: 10px;
  line-height: 1.2;
}

.card-desc {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #999;
}

.date-range {
  color: #1890ff;
}

/* 图表容器样式 */
.chart-container {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

/* 图表项样式 */
.chart-item {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto 30px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

/* 图表标题样式 */
.chart-title {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
  font-size: 18px;
  font-weight: 600;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

/* 图表容器样式 */
.chart-wrapper {
  width: 100%;
  height: 500px;
  border-radius: 4px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .dashboard-container {
    padding: 10px;
  }

  .data-overview {
    gap: 10px;
    margin-bottom: 20px;
  }

  .overview-card {
    padding: 15px;
    min-width: 100%;
  }

  .card-value {
    font-size: 24px;
  }

  .chart-container {
    padding: 10px;
  }

  .chart-item {
    padding: 15px;
    margin-bottom: 20px;
  }

  .chart-wrapper {
    height: 400px;
  }

  .chart-title {
    font-size: 16px;
  }
}
</style>